#!/usr/bin/env bash
# Repkit Loops .app entrypoint — headless API + pinned Electron shell.
# Installed as Contents/MacOS/repkit-loops inside the release bundle.
set -euo pipefail

MACOS="$(cd "$(dirname "$0")" && pwd)"
CONTENTS="$(cd "${MACOS}/.." && pwd)"
HELPERS="${CONTENTS}/Helpers"
API_BIN="${HELPERS}/kitsune-desktop"
LAUNCHER="${HELPERS}/electron-launcher"
SHELL_DIR="${HELPERS}/electron-shell"
PORT="${KITSUNE_DESKTOP_PORT:-8090}"
URL="http://127.0.0.1:${PORT}"

export KITSUNE_DESKTOP_WEBVIEW=false
export KITSUNE_DESKTOP_SHELL=electron
export KITSUNE_ELECTRON_LAUNCHER="$LAUNCHER"
export WEBVIEW_ELECTRON_SHELL_DIR="$SHELL_DIR"

if [[ ! -x "$API_BIN" || ! -x "$LAUNCHER" || ! -f "${SHELL_DIR}/main.js" ]]; then
  echo "Repkit Loops bundle is incomplete (missing Electron helpers)." >&2
  exit 1
fi

# Secondary instances (--new-window) are spawned by the API; they open their own Electron window.
for arg in "$@"; do
  if [[ "$arg" == "--new-window" ]]; then
    exec "$API_BIN" "$@"
  fi
done

cleanup() {
  if [[ -n "${API_PID:-}" ]] && kill -0 "$API_PID" 2>/dev/null; then
    kill "$API_PID" 2>/dev/null || true
    wait "$API_PID" 2>/dev/null || true
  fi
}
trap cleanup EXIT INT TERM

"$API_BIN" &
API_PID=$!

deadline=$((SECONDS + 45))
until curl -sf "${URL}/health" >/dev/null 2>&1; do
  if ! kill -0 "$API_PID" 2>/dev/null; then
    echo "Repkit Loops API exited before ${URL}/health was ready." >&2
    exit 1
  fi
  if (( SECONDS >= deadline )); then
    echo "Timed out waiting for ${URL}/health." >&2
    exit 1
  fi
  sleep 0.2
done

exec "$LAUNCHER" --url "$URL" --title "Repkit Loops" --width 1100 --height 760
